package com.pnnd.utils;

import com.pnnd.StreamLenException;

import java.io.*;

public class BytesUtils {

    private BytesUtils(){}

    public static int bytes2Int(byte[] bytes,int start,int elementLength){
        if(bytes.length < elementLength){
            throw new StreamLenException("bytes");
        }

        int sum = 0;

        int end = start + elementLength;

        for (int i = start; i < end; i++) {
            int n = ((int)bytes[i]) & 0xff;

            n <<= (elementLength - i) * 8;

            sum += n;

        }

        return sum;
    }

    public static long bytes2Long(byte[] bytes,int start,int elementLength){

        if(bytes.length < elementLength){
            throw new StreamLenException("bytes");
        }

        long sum = 0;

        int end = start + elementLength;

        for (int i = start; i < end; i++) {
            long n = ((int)bytes[i]) & 0xff;

            n <<= (elementLength - i) * 8;

            sum += n;

        }

        return sum;
    }

    public static short bytes2Short(byte[] bytes,int start,int elementLength){
        return (short)bytes2Int(bytes,start,elementLength);
    }

    public static String bytes2String(byte[] bytes,int start,int elementLength) {
        ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes,start,elementLength);

        new InputStreamReader(inputStream);

        DataInputStream dataInputStream = new DataInputStream(inputStream);

        try {
            return dataInputStream.readUTF();
        } catch (IOException ioException) {
            throw new RuntimeException(ioException);
        }
    }

}
